// 导入cookie操作的获取与设置方法
import { getToken, setToken } from '@/utils/auth'
// 导入api封装的登录接口
import { sysLogin } from '@/api/login.js'
// 导入用户基本信息
import { sysProfile, sysUser } from '@/api/user.js'
import { Message } from 'element-ui'
// !!!导入需要管理权限的路由与router
import asyncRoutes from '@/router/modules/index.js'
import Router from '@/router'
// 导入静态路由
import { constantRoutes, resetRouter } from '@/router'
const state = {
  token: getToken() || '',
  userInfo: ''
}
const mutations = {
  setToken(state, value) {
    state.token = value
    setToken(value)
  },
  setuserInfo(state, value) {
    state.userInfo = value
  },
  // 在屌用自己的方法
  login() {
    // 这里的this===this.$store
    this.commit('user/setToken', '')
    this.commit('user/setuserInfo', '')
    resetRouter()
  }
}
const getters = {}
const actions = {
  // 把登录页面请求的值,拿过来
  async toLogin(content, form) {
    const res = await sysLogin(form)
    Message.success('登录成功')
    content.commit('setToken', res.data)
    console.log(res, 555)
    console.log(res.data, 222)
  },
  // 获取用户基本信息
  async getuserInfo({ commit }) {
    // 获取用户基本信息
    const res = await sysProfile()
    // 获取用户基本信息,包含图片{ ...res.data, ...res2.data }
    const res2 = sysUser(res.data.userId)
    commit('setuserInfo', Object.assign({}, res.data, res2.data))
    console.log(res.data.roles.menus, 999)
    // res.data.roles.mens
    const newArr = asyncRoutes.filter((item) => {
      return res.data.roles.menus.includes(item.meta.name)
    })
    // assRoutes需要再调用一次导航守卫后才可以正常访问
    Router.addRoutes([...newArr, { path: '*', redirect: '/404', hidden: true }])
    const allRoutes = [...constantRoutes, ...newArr, { path: '*', redirect: '/404', hidden: true }]
    commit('routes/setRoutesList', allRoutes, { root: true })
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  getters,
  actions
}
